/**
 * Licensed to the Apache Software Foundation (ASF) under one or more
 * contributor license agreements.  See the NOTICE file distributed with
 * this work for additional information regarding copyright ownership.
 * The ASF licenses this file to You under the Apache License, Version 2.0
 * (the "License"); you may not use this file except in compliance with
 * the License.  You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.polarrose.spring.bayeux;

import com.polarrose.spring.bayeux.util.BayeuxUtil;
import com.polarrose.spring.bayeux.util.JsonUtil;
import dojox.cometd.Bayeux;
import dojox.cometd.Client;
import dojox.cometd.Message;
import dojox.cometd.MessageListener;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Required;

/**
 * @author Stefan Arentz
 */

public class BayeuxServiceContainer implements InitializingBean
{
    /**
     *
     */

    private BayeuxServer bayeuxServer;

    @Required
    public void setBayeuxServer(BayeuxServer bayeuxServer)
    {
        this.bayeuxServer = bayeuxServer;
    }

    /**
     *
     */

    private BayeuxChannel channel;

    @Required
    public void setChannel(BayeuxChannel channel)
    {
        this.channel = channel;
    }

    /**
     *
     */

    private String name;

    @Required
    public void setName(String name)
    {
        this.name = name;
    }

    /**
     *
     */

    private BayeuxService service;

    @Required
    public void setService(BayeuxService service)
    {
        this.service = service;
    }

    //

    private BayeuxClient client;

    public BayeuxClient getClient()
    {
        return client;
    }

    //

    private Class<?> handlerDataClass;

    public void afterPropertiesSet() throws Exception
    {
        client = new BayeuxClient(bayeuxServer, name);
        client.addListener(new BayeuxServiceListener());

        channel.subscribe(client);

        handlerDataClass = BayeuxUtil.getBayeuxServiceDataClass(service);
        if (handlerDataClass == null) {
            throw new RuntimeException("Cannot determine data class of the BayeuxServiceContainer subclass " + this.getClass().getName());
        }
    }

    //

    private void deliver(Client from, Message message)
    {
        Object data = message.getData();

        if (client.getClient() != from) {
            if (handlerDataClass != null) {
                data = JsonUtil.transmogrify(handlerDataClass, data, null);
            }

            //noinspection unchecked
            Object result = service.handle(channel, new BayeuxClient(bayeuxServer, from), getClient(), data);
            if (result != null) {
                String id = (String) message.get(Bayeux.ID_FIELD);
                // XXX Don't call client directly here .. use BayeuxClient.deliver instead - XXX What is the id for? Does not seem to matter ...
                from.deliver(getClient().getClient(), channel.getName(), result, id);
            }
        }
    }

    //

    private class BayeuxServiceListener implements MessageListener
    {
        public void deliver(Client from, Client to, Message message)
        {
            BayeuxServiceContainer.this.deliver(from, message);
        }
    }

}